package com.ktjiaoyu.utils.fastjson2;

import com.alibaba.fastjson2.filter.ValueFilter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Set;
//处理日期格式过滤器
public class FastJson2DateValueFilter implements ValueFilter {
    public FastJson2DateValueFilter(LinkedHashMap<String, String> dateMappings) {
        this.dateMappings = dateMappings;
    }

    private LinkedHashMap<String, String> dateMappings;

    @Override
    public Object apply(Object object, String properName, Object value) {
        if (dateMappings == null) {
            return value;
        }
        //判断数据类型,只处理Date类型
        if (value instanceof Date) {
            Set<String> ketSet = dateMappings.keySet();
            for (String pattern : ketSet) {
                //判断字段名是否符合条件   如：createTime
                if (properName.matches(pattern)) {
                    //符合条件的日期格式进行转换
                    String dataFormat = dateMappings.get(pattern);
                    //返回对应格式
                    SimpleDateFormat formatter = new SimpleDateFormat(dataFormat);
                    //将日期转换为字符串返回
                    return formatter.format((Date) value);
                }
            }
        }
        return value;
    }
}
